package com.bangdream.michelia.view.activity.questionnaire;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.andview.refreshview.XRefreshView;
import com.bangdream.michelia.R;
import com.bangdream.michelia.application.AppCurrentUser;
import com.bangdream.michelia.application.AppQuestData;
import com.bangdream.michelia.contract.ExamContract;
import com.bangdream.michelia.entity.BaseEntity;
import com.bangdream.michelia.entity.QuestAnswerBean;
import com.bangdream.michelia.entity.exam.AnswerBean;
import com.bangdream.michelia.entity.exam.ExamBean;
import com.bangdream.michelia.entity.exam.ExamQuestBean;
import com.bangdream.michelia.entity.exam.ExamResultDetailsBean;
import com.bangdream.michelia.entity.exam.ExamResultItemBean;
import com.bangdream.michelia.entity.exam.SubjectBean;
import com.bangdream.michelia.entity.exam.SubjectInfoBean;
import com.bangdream.michelia.presenter.ExamPresenter;
import com.bangdream.michelia.tool.retrofithttp.RetroFactory;
import com.bangdream.michelia.tool.retrofithttp.TokenManagerDef;
import com.bangdream.michelia.utils.ToastUtil;
import com.bangdream.michelia.view.activity.base.SwipeBackActivity;
import com.bangdream.michelia.view.activity.exam.ExamActivity;
import com.bangdream.michelia.view.adapter.ListItemClickHelp;
import com.bangdream.michelia.view.adapter.QuestListAdapter;
import com.nanchen.compresshelper.StringUtil;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * @date on 2018/8/11 2:14
 * @email 909732184@qq.com
 * 问卷调查
 */
public class QuestionnaireActivity extends SwipeBackActivity<ExamContract.IExamView,ExamPresenter<ExamContract.IExamView>> implements ExamContract.IExamView,QuestListAdapter.OnItemClickListener,ListItemClickHelp {
    private RecyclerView recyclerView;
    private LinearLayoutManager linearLayoutManager;
    private XRefreshView refreshView;
    private QuestListAdapter adapter;
    private List<ExamQuestBean> questList;
    private String examId="";
    private String paperId="";
    private String strTitle="";
    private String planUserItemId="";
    @Override
    public int getLayout() {
        return R.layout.activity_quest;
    }

    @Override
    public void findId() {

    }

    @Override
    public void setListener() {
        Bundle bundle = getIntent().getExtras();
        String id =  bundle.getString("id");
        paperId  =  bundle.getString("paperId");
        strTitle = bundle.getString("title");
        planUserItemId = bundle.getString("planUserItemId");
        if(strTitle.equals("")){
            initTitleBar(" ","问卷调查主题名称","",this);
        }else{
            initTitleBar(" ",strTitle,"",this);
        }
        mPresenter.initExamId(id,null);
    }

    @Override
    public void logic() {
//        initTitleBar(" ","问卷调查主题名称","",this);
        refreshView = findViewById(R.id.refreshView);
        refreshView.setPullLoadEnable(false);
        refreshView.setPullRefreshEnable(false);
        recyclerView = findViewById(R.id.recyclerView);
        linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        questList= new ArrayList<>();
        AppQuestData.getInstance().getQuestAnswerList().clear();
        adapter = new QuestListAdapter(this,this,questList);
        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(this);

    }
    @Override
    public void onClick(int position, int which ) {
        Log.i("选择的数字为-","-----");
        if(which==R.id.btnGo){
            if(adapter.getItemViewType(position)==5){ //提交按钮
//            for(){
                List<QuestAnswerBean> questList = AppQuestData.getInstance().getQuestAnswerList();
                if(questList.size()==0){
                    ToastUtil.showShortToast(this,"您还没有答题");
                    return;
                }
                AnswerBean bean = new AnswerBean();
                bean.setAnswer(linkStr(questList));
                bean.setPaperId(paperId);
                bean.setExamId(examId);
                bean.setUserId(AppCurrentUser.getInstance().getUserInfo().getId());
                JSONArray array = (JSONArray) JSONArray.toJSON(questList);
                Log.i("选择的数字为array",""+linkStr(questList));
                mPresenter.actionSubmitQuest(bean,false,null);
            }
        }
    }
    private String linkStr(List<QuestAnswerBean> questList){
        Collections.sort(questList, new Comparator<QuestAnswerBean>() {
            @Override
            public int compare(QuestAnswerBean p1, QuestAnswerBean p2) {
                if(p1.getPosition() > p2.getPosition()){
                    return 1;
                }
                if(p1.getPosition() == p2.getPosition()){
                    return 0;
                }
                return -1;
            }
        });
        JSONArray array = (JSONArray) JSONArray.toJSON(questList);
        Log.i("questList集合",""+array.toString());
        String str ="";
        for(int i=0;i<questList.size();i++){
            QuestAnswerBean bean = questList.get(i);
            str+=bean.getInfoId()+"|"+bean.getId()+"|"+bean.getAnswer();
            if(questList.size()!=i+1){
                str+=",";
            }
        }
        return str;
    }

    @Override
    public ExamPresenter<ExamContract.IExamView> createPresenter() {
        return new ExamPresenter();
    }

    @Override
    public void setExamList(boolean isSuccess, int page, List<ExamBean> data, String stDescribe) {

    }

    @Override
    public void setSubjectList(boolean isSuccess, List<SubjectBean> data, String stDescribe) {

    }

    @Override
    public void setSubjectDetails(boolean isSuccess, SubjectInfoBean data, String stDescribe) {

    }

    @Override
    public void initExamId(boolean isSuccess, String examId, String stDescribe) {
        Log.i("examId---",""+examId);
        this.examId = examId;
        mPresenter.getExamQuestList(examId,null);

        if(!StringUtil.isEmpty(planUserItemId)){
            bindExam(examId,planUserItemId);
        }

    }
    @Override
    public void actionSubmitExam(boolean isSuccess, boolean isFinish, String stDescribe) {

    }

    @Override
    public void actionSubmitQuest(boolean isSuccess, boolean isFinish, String stDescribe) {
        if(isSuccess){
            ToastUtil.showShortToast(this,""+"提交成功");
            AppQuestData.getInstance().getQuestAnswerList().clear();
            finish();
        }
    }

    @Override
    public void setExamResultList(boolean isSuccess, List<ExamResultItemBean> data, String stDescribe) {

    }

    @Override
    public void setExamResultDetails(boolean isSuccess, ExamResultDetailsBean data, String stDescribe) {

    }

    @Override
    public void setExamQuestList(boolean isSuccess, List<ExamQuestBean> data, String stDescribe) {
        if(isSuccess){
            questList = data;
            if(data!=null)
            adapter.notifyDataChange(questList);
        }

    }

    @Override
    public void setExamQuList(boolean isSuccess, List<ExamBean> data, String stDescribe) {

    }

    @Override
    public void onQrderItemClick(int position) {
//        Log.i("选择的数字为--",":");

    }


    private void bindExam(String examId, String planUserItemId){
        Map map=new HashMap();
        map.put("id", planUserItemId);
        map.put("examId", examId);

        String jsonString = JSON.toJSONString(map);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),jsonString);

        TokenManagerDef.work(() ->
                RetroFactory.getInstance().bindExamByTran(AppCurrentUser.getInstance().getToken(),requestBody))
                .compose(TokenManagerDef.newInstance().getTransformer())
                .compose(composeFunction)
                .subscribe(new Observer<BaseEntity>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(BaseEntity o) {
                        pd.cancel();
                        if(o.isOk()){

                        }else{
                            ToastUtil.showShortToast(QuestionnaireActivity.this,"绑定任务计划失败");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        pd.cancel();
                        ToastUtil.showShortToast(QuestionnaireActivity.this,"绑定任务计划失败");
                    }

                    @Override
                    public void onComplete() { }
                });
    }


}
